<script setup>
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import MyUpload from '@/components/MyUpload.vue'
import { caseDocumentServer, uploadCaseDocument } from '@/api/arrears'

const props = defineProps({
  info: {
    type: Object,
  }
})

const loading = ref(false)
const list = ref([])
const getFileList = async () => {
  if (!props.info?.arrears_data_id) {
    return
  }
  loading.value = true
  try {
    const { data } = await caseDocumentServer.get({ arrears_data_id: props.info.arrears_data_id })
    list.value = data || []
  } catch (error) {
    ElMessage.error('获取文书列表失败')
  }
  loading.value = false
}
getFileList();


const selectedRows = ref([])
// 勾选变化时触发
function handleSelectionChange(val) {
  selectedRows.value = val
}
// 批量下载
function handleDownload() {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要下载的文书')
    return
  }
  selectedRows.value.forEach(item => {
    downloadFile(item.url)
  })
}

// 上传文件
async function onUploadFile(file) {
  await uploadCaseDocument({
    arrears_data_id: props.info.arrears_data_id,
    file: file[0]
  })
  ElMessage.success('上传成功')
  getFileList()
}

// 下载
function downloadFile(url) {
  const link = document.createElement('a')
  link.href = url
  link.target = '_blank'
  link.download = ''
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  ElMessage.success('下载成功')
}

// 删除 
const handleDelete = async (row) => {
  await ElMessageBox.confirm('确定要删除该文件吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  await caseDocumentServer.delete({ document_id: row.document_id })
  ElMessage.success('删除成功')
  getFileList()

}

const hideName = (name) => {
  if (!name) return ''
  const parts = name.split('.')
  if (parts.length < 2) return name
  const ext = parts.pop()
  const baseName = parts.join('.')
  if (baseName.length > 10) {
    return `${baseName.slice(0, 10)}...${ext}`
  }
  return `${baseName}.${ext}`
}
const getSize = (size) => {
  if (!size) return ''
  if (size < 1024) return `${size} B`
  if (size < 1024 * 1024) return `${(size / 1024).toFixed(2)} KB`
  return `${(size / (1024 * 1024)).toFixed(2)} MB`
}
</script>

<template>
  <div>
    <div class="flex justify-end mb-3 gap-3">
      <MyUpload @change="onUploadFile">
        <el-button type="primary">上传</el-button>
      </MyUpload>
      <el-button type="primary" @click="handleDownload">批量下载</el-button>
    </div>
    <el-table :data="list" v-loading="loading" @selection-change="handleSelectionChange" max-height="400px"
      :show-header="false">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="filename" label="文件名">
        <template #default="{ row }">
          <el-tooltip type="dark" :content="row.filename" placement="top">
            <span>{{ hideName(row.filename) }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="size" label="大小">
        <template #default="{ row }">
          <span>{{ getSize(row.size) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="add_user_name" label="上传人" />
      <el-table-column prop="add_time" label="上传时间" />
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button text type="primary" @click="downloadFile(row.url)">下载</el-button>
          <el-button text type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>